package com.yanghui.dtracing.plugin.mybatisPlus;

import com.baomidou.mybatisplus.core.override.MybatisMapperProxy;
import com.yanghui.dtracing.core.constant.TypeEnum;
import com.yanghui.dtracing.core.opentracing.DTracerSpan;
import com.yanghui.dtracing.core.opentracing.DTracerTags;
import com.yanghui.dtracing.core.plugin.interceptor.AbstractInstanceMethodInterceptor;
import com.yanghui.dtracing.core.plugin.interceptor.MethodInterceptResult;
import io.opentracing.Span;
import io.opentracing.tag.Tags;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MybatisPlusInstanceMethodAroundInterceptor extends AbstractInstanceMethodInterceptor {

    @Override
    protected void doBeforeMethod(Object thisObj, Method method, Object[] allArguments, MethodInterceptResult result, Span span) throws Throwable {
        span.setTag(Tags.COMPONENT, DTracerTags.COMPONENT_MYBATISPLUS)
                .setTag(DTracerTags.TYPE, TypeEnum.LOCAL.getName());
        Field targetField = thisObj.getClass().getSuperclass().getDeclaredField("h");
        targetField.setAccessible(true);
        MybatisMapperProxy proxy = (MybatisMapperProxy)targetField.get(thisObj);

        Field mapperInterfaceField = proxy.getClass().getDeclaredField("mapperInterface");
        mapperInterfaceField.setAccessible(true);
        Class clz = (Class)mapperInterfaceField.get(proxy);

        DTracerSpan tracerSpan = (DTracerSpan)span;
        tracerSpan.setClassName(clz.getName());
    }
}
